package com.hysf.dao.impl;

import com.hysf.dao.OpRecordDao;
import com.hysf.pojo.OpRecord;
import com.hysf.utils.DateFormat;
import com.hysf.utils.OpRecordRowMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Repository
@RequiredArgsConstructor
public class OpRecordDaoImpl implements OpRecordDao {
	
	private final JdbcTemplate jdbcTemplate;
	
	@Override
	public void insertOpRecord(OpRecord opRecord) {
		String sql = "insert into oprecord (accountid, opmoney, optime, optype,transferid) values (?, ?, ?, ?, ?)";
		Date date = DateFormat.parse(opRecord.getOptime());
		jdbcTemplate.update(sql, opRecord.getAccountid(), opRecord.getOpmoney(), date, opRecord.getOptype().getValue(), opRecord.getTransferid());
	}
	
	@Override
	public List<OpRecord> findOpRecord(int accountid) {
		String sql = "select * from oprecord where accountid = ? order by optime desc";
		return jdbcTemplate.query(sql, new OpRecordRowMapper(), accountid);
	}
	
	@Override
	public List<OpRecord> findOpRecord(int accountid, String opType) {
		String sql = "select * from oprecord where accountid = ? and optype = ? order by optime desc";
		return jdbcTemplate.query(sql, new OpRecordRowMapper(), accountid, opType);
	}
	
	@Override
	public List<OpRecord> findOpRecord(OpRecord opRecord) {
		String sql = "select * from oprecord where 1 = 1";
		List<Object> params = new ArrayList<>();
		if (opRecord.getAccountid() != -1) {
			sql += " and accountid = ?";
			params.add(opRecord.getAccountid());
		}
		if (opRecord.getOptype() != null) {
			sql += " and optype = ?";
			params.add(opRecord.getOptype().getValue());
		}
		if (opRecord.getOptime() != null) {
			sql += " and optime >= ?";
			Date date = DateFormat.parse(opRecord.getOptime());
			params.add(date);
		}
		sql += " order by optime desc";
		System.out.println(sql);
		return jdbcTemplate.query(sql, new OpRecordRowMapper(), params.toArray());
	}
}
